#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/11/2 13:24
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : weichat_openid.py
# @Software: PyCharm
# @Desc    :
import time
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.generics import GenericAPIView

from common.utils.pagination import EnhancedPageNumberPagination
from common.utils.rsp import success_response
from wechat.filters.filter_wechat_template import WechatTemplateFilter
from wechat.models import WechatTemplate,WechatOpenid
from wechat.sers.ser_wechat_template import WechatTemplateSerializer
from wechat.utils.tool_wechat import WeChatMessageSender


class WechatOpenidListCreateView(GenericAPIView):
    """
    WechatTemplate列表查询 + 新增接口
    - GET: 分页查询微信模板列表（支持过滤、排序）
    - POST: 新增微信模板（自动校验标题和模板ID唯一性）
    """
    # 仅查询“未删除+非压测”的有效数据，与EmailConfig逻辑对齐
    queryset = WechatTemplate.objects.filter(is_delete=0, pt_flag=0).all()
    serializer_class = WechatTemplateSerializer
    pagination_class = EnhancedPageNumberPagination  # 复用通用分页器

    # 过滤与排序配置：支持按名称、AppID筛选，按创建时间/排序号排序
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_class = WechatTemplateFilter
    ordering_fields = ["create_time", "name", "sort_num", "is_active"]
    # 默认排序：按创建时间倒序，新模板在前
    ordering = ["-create_time"]

    def get(self, request, *args, **kwargs):
        """GET请求：分页查询微信模板列表"""
        # 1. 过滤数据（按筛选条件）
        filtered_qs = self.filter_queryset(self.get_queryset())
        # 2. 分页处理
        page_qs = self.paginate_queryset(filtered_qs)
        # 3. 序列化数据
        serializer = self.get_serializer(page_qs, many=True)
        # 4. 组装分页响应（复用分页器的分页结构）
        paginated_data = self.paginator.get_paginated_response(serializer.data).data

        return success_response(
            data=paginated_data,
            message="微信模板列表查询成功"
        )

    def post(self, request, *args, **kwargs):
        """POST请求：新增微信模板"""
        # 1. 数据校验（触发序列化器的name/template_id唯一性校验）
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 2. 保存数据
        serializer.save()

        return success_response(
            data=serializer.data,
            message=f"微信模板「{serializer.validated_data['name']}」创建成功"
        )


class WechatTemplateRetrieveUpdateDestroyView(GenericAPIView):
    """
    WechatTemplate单条操作接口
    - GET: 查询单个微信模板详情
    - PUT: 全量更新微信模板（需传所有必填字段）
    - PATCH: 部分更新微信模板（仅传需修改的字段）
    - DELETE: 逻辑删除微信模板（设置is_delete=1）
    """
    queryset = WechatTemplate.objects.all()
    serializer_class = WechatTemplateSerializer
    lookup_field = "pk"  # 按主键ID查询

    def get_object(self):
        """重写：仅允许操作“未删除+非压测”的有效数据，不存在则抛错"""
        instance = super().get_object()
        if instance.is_delete == 1 or instance.pt_flag == 1:
            raise ValueError("当前微信模板不存在或已被删除，无法操作！")
        return instance

    def get(self, request, *args, **kwargs):
        """GET请求：查询单个微信模板详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message="微信模板详情查询成功")

    def put(self, request, *args, **kwargs):
        """PUT请求：全量更新微信模板（需传所有必填字段）"""
        instance = self.get_object()
        # partial=False：全量更新，必须传所有required字段
        serializer = self.get_serializer(instance, data=request.data, partial=False)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return success_response(
            data=serializer.data,
            message=f"微信模板「{instance.name}」全量更新成功"
        )

    def patch(self, request, *args, **kwargs):
        """PATCH请求：部分更新微信模板（仅传需修改的字段）"""
        instance = self.get_object()
        # partial=True：部分更新，无需传所有字段
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return success_response(
            data=serializer.data,
            message=f"微信模板「{instance.name}」部分更新成功"
        )

    def delete(self, request, *args, **kwargs):
        """DELETE请求：逻辑删除微信模板（不物理删除数据）"""
        instance = self.get_object()
        template_name = instance.name
        # 设置逻辑删除标识，与EmailConfig删除逻辑一致
        instance.is_delete = 1
        instance.save()

        return success_response(
            data=None,
            message=f"微信模板「{template_name}」已成功删除（逻辑删除）"
        )